#include <iostream>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define FILENAME ".fifo"

using namespace std;

bool MakeFifo()
{
    int n = mkfifo(FILENAME, 0666);
    if(n < 0)
    {
        std::cerr << "errno: " << errno <<", errstring: " << strerror(errno) << std::endl;
        return false;
    }
    std::cout << "mkfifo sucess..." << std::endl;
    return true;
}

int main()
{
Start:
    int rfd = open(FILENAME, O_RDONLY);
    if( rfd < 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) <<std::endl;
        if(MakeFifo())
            goto Start;
        else return 1;
    }
    std::cout << "open fifo sucess...r" << std::endl;

    char buffer[1024];

    while(1)
    {
        ssize_t s = read(rfd, buffer ,sizeof(buffer)-1);
        if(s > 0)
        {
            buffer[s] = 0;//加'\0'
            std::cout << "Cilent say# " << buffer << std::endl;
        }
        else if(s == 0)
        {
            std::cout << "client quit,server quit!" << std::endl;
            break;
        }
    }
    close(rfd);
    std::cout << "close rfd sucess..." << std::endl;

    return 0;
}